package org.netty.demo.lihh.notice.strategy.impl;

import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import org.netty.demo.lihh.notice.domain.ClientMsgProtocol;
import org.netty.demo.lihh.notice.strategy.StrategyHandle;
import org.netty.demo.lihh.notice.util.ChannelHandler;
import org.netty.demo.lihh.notice.util.MsgUtil;

import java.util.ArrayList;
import java.util.List;

public class ConnectStrategyImpl implements StrategyHandle {
  @Override
  public void accept(ClientMsgProtocol dto) {
    String roleId = dto.getRoleId(), tk = dto.getTk(), innerChannelId = dto.getChannelId();
    
    // 持久化 roleId、tk，channelId，channel 之间的关系
    ChannelHandler.addChannel(roleId, tk, innerChannelId);
    
    List<Channel> channelRecords = ChannelHandler.getChannelExcludeChannelId(roleId, new ArrayList<>());
    // 给每个客户端 发送其他用户登录成功的消息
    channelRecords.forEach(channel -> {
      SocketChannel socketChannel = (SocketChannel) channel;
      socketChannel.writeAndFlush(MsgUtil.buildConnectSuccessServerResponseMsg(innerChannelId, tk));
    });
  }
}
